package cn.cqnu.utils;


import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import cn.cqnu.global.SystemConstant;

/**
 * OSS文件操作工具类
 *
 * @author Wei
 * @date 2024/01/01
 */
public class OSSUtil {

    private OSSUtil() {
    }

//    public static void main(String[] args) throws Exception {
//        File file = new File("E:\\abc.png");
//        FileInputStream fileInputStream = new FileInputStream(file);
//        System.out.println("新头像：：：");
//        System.out.println(uploadFile(fileInputStream, SystemConstant.OSS_AVATAR_PATH, "copy2.jpeg"));
//    }

    public static String uploadFile(InputStream inputStream, String path, String fileName) throws Exception {

        // 填写Bucket名称，例如examplebucket。
        String bucketName = SystemConstant.OSS_BUCKET;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(
                SystemConstant.OSS_ENDPOINT,
                SystemConstant.OSS_ACCESSKEY_ID,
                SystemConstant.OSS_ACCESSKEY_SECRET
        );

//        是否失败
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, path + fileName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            //拼接图片访问地址
            String imageUrl = SystemConstant.OSS_VISIT_URL + path + fileName;

            return imageUrl;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return "";
    }

}